package com.imooc.exceptions;

import com.imooc.grace.result.GraceJSONResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器:拦截抛出的异常，并序列化为JSON数据返回给前端
 */
@RestControllerAdvice
public class GraceExceptionHandler {

    /**
     * 自定义异常 处理器
     * 返回给前端异常信息
     */
    @ExceptionHandler(value = MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyCustomException(MyCustomException e) {
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }

    /**
     * 字段校验异常 处理器
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnMyCustomException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errors = getErrors(bindingResult);
        return GraceJSONResult.errorMap(errors);
    }

    private Map<String, String> getErrors(BindingResult bindingResult) {

        Map<String, String> map = new HashMap<>();

        bindingResult.getFieldErrors().forEach((fieldError) -> {
            String fieldName = fieldError.getField();
            String errorMsg = fieldError.getDefaultMessage();
            map.put(fieldName, errorMsg);
        });

        return map;
    }
}
